package com.hulk.rpc.trace;

import com.hulk.rpc.utils.concurrent.AttachmentThreadUtils;
import com.hulk.rpc.utils.uuid.ObjectId;

import java.util.concurrent.ThreadLocalRandom;

/**
 * tracer上下文
 */
public class TracerContext {

  private static final int ATTACHMENT_INDEX = AttachmentThreadUtils.nextVarIndex();

  /**
   * 设置tracer上下文，后续请求将会作为parent使用
   */
  public static void setTracer(Tracer tracer) {
    AttachmentThreadUtils.put(ATTACHMENT_INDEX, tracer);
  }

  /**
   * 如果有parent，会自动设置上
   */
  public static Tracer nextTracer() {
    Tracer tracerContext = AttachmentThreadUtils.get(ATTACHMENT_INDEX);

    Tracer tracer = new Tracer();
    tracer.setSpanId(ThreadLocalRandom.current().nextLong());

    if (tracerContext != null) {
      tracer.setTraceId(tracerContext.getTraceId());
      tracer.setParentId(tracerContext.getSpanId());
    } else {
      tracer.setTraceId(ObjectId.next());
      tracer.setParentId(0);
    }

    return tracer;
  }
}
